package com.xctech.yace.service;

import com.xctech.yace.util.DirUtil;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelService {

    public static void main(String[] args) {
        saveExcel("ceshi","test",1l);
    }

    public static String dir = DirUtil.getOrgPath()+"conf/resultexcel/";

    public static void saveExcel(ConsumerRecord<String, String> info){
        String value = info.value();
        saveExcel(value,info.topic(),info.offset());
    }

    public static void saveExcel(String value,String topic,Long offset){

        FileOutputStream out = null;
        try{
            String fileName = dir+topic+".xlsx";
            File file = new File(fileName);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();// 能创建多级目录
            }
            if (!file.exists()) {
                System.out.println("正在创建!");
                try {
                    file.createNewFile();//有路径才能创建文件
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //解析json到对象
//            genDataFromJson(value);

            //创建工作簿
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook();

            //创建工作表
            //将源数据生成到第一个sheet页
            XSSFSheet xssfSheet = xssfWorkbook.createSheet("source");

            XSSFSheet xssfSheet1 = xssfWorkbook.createSheet("source1");
            XSSFSheet xssfSheet2 = xssfWorkbook.createSheet("source2");

            XSSFRow row = xssfSheet.createRow(0);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue(offset);
            cell = row.createCell(1);
            cell.setCellValue(value);


            //把List里面的数据写到excel中
//            for (int i=0;i<list.size();i++) {
//                //从第一行开始写入
//                xssfRow = xssfSheet.createRow(i);
//                //创建每个单元格Cell，即列的数据
//                List sub_list =list.get(i);
//                for (int j=0;j<sub_list.size();j++) {
//                    xssfCell = xssfRow.createCell(j); //创建单元格
//                    xssfCell.setCellValue((String)sub_list.get(j)); //设置单元格内容
//                }
//            }


            out = new FileOutputStream(fileName,true);
            xssfWorkbook.write(out);
            out.flush();
            System.out.println("数据写入完毕!");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
